<!--vue模板-->
<template>
  <el-dialog
    :model-value="visible"
    title="新增部门"
    width="600"
    :close-on-click-modal="false"
    @close="cls"
  >
    <el-form
      ref="formRel"
      :model="data"
      :rules="rules"
      label-width="100px"
      style="max-width: 600px"
    >
      <el-form-item label="上级部门">
        <el-input v-model="data.parentName" disabled />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="data.name" />
      </el-form-item>
    </el-form>

    <div style="text-align: right">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="info" @click="cls">取消</el-button>
    </div>
  </el-dialog>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { saveDept } from "@/api/dept.js";

//表单引用
const formRel = ref(null);

//响应式对象
const data = ref({
  parentId: 0,
  parentName: "",
  name: ""
});
//定义属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
//声明事件
const emits = defineEmits(["close", "refresh"]);

//验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
});

//方法
function cls() {
  //通知父组件  我要关闭了
  emits("close");
}

//保存
async function save() {
  //验证 valid=false 说明验证未通过
  const valid = await formRel.value.validate(() => {});
  if (!valid) return;

  //保存部门
  //console.log("user>>>", user.value);
  let res = await saveDept(data.value);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    //通知父组件刷新数据
    emits("refresh");
    cls();
  }
}
function init(parentId, parentName) {
  data.value.name = "";
  data.value.parentId = parentId;
  data.value.parentName = parentName;
}
defineExpose({ init });
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped></style>
